$(function(){
	$("#toSearch").click(function(){
		location.href = "shoppingCart.html";
		/*var _keyword = $(this).prev().find("input").val();
		if(_keyword != ""){
			//sessionStorage.getItem("keyword",_keyword);
			_keyword = encodeURI(_keyword); 
			_keyword = encodeURI(_keyword); 
			location.href = "searchResult.html?keyword=" + _keyword;
		}*/
	})
})

var app = angular.module("myApp",["globalApp"]);

app.controller("myCtrl",function($scope,$http){
	$scope.reminder = false; 
	//当搜索框被点击时跳到搜索记录页面
	$scope.toFind = function(){
		location.href = "search_record.html";
	}
	
	//隐藏提示框
	$scope.close = function(){
    	$scope.reminder = false;
    }
	
	$scope.choiceness_goods = $scope.farm_products= $scope.agricultural = [];
	
	$http({
        type : "get",
        dataType: "json",
		withCredentials: true,	//跨域名请求。XHR：XMLHttpRequest (XHR) ，基于XML技术的Http请求
	    crossDomain: true,
	    contentType: "application/json",
        //async:true,
        url : host + "/terminal/goods/homePage"
    }).success(function(response){
        if(response.code == 2000){
        	$scope.choiceness_goods = response.data.catagories[0].goods;
        	$scope.farm_products = response.data.catagories[1].goods;
        	$scope.agricultural = response.data.catagories[2].goods;
        }
    });
    
    
    $scope.setCart = function(k){
        
    	var code = k.code;
    	k.num = 1;
    	//对购物车的请求，查看是否存在该商品，并获得num
    	$http({
    		method : "get",
    		withCredentials: true,	//跨域名请求。XHR：XMLHttpRequest (XHR) ，基于XML技术的Http请求
		    crossDomain: true,
		    async : false,
		    contentType: "application/x-www-form-urlencoded",//表单提交
		    url : host + "/terminal/shoppingCart/list"
    	}).success(function(response){
    		console.log(response)
    		if(response.code == 2000){
    			for(var i=0; i<response.data.shoppingCarts.length; i++){
	    			if(code == response.data.shoppingCarts[i].goods.code){
		    			k.num = response.data.shoppingCarts[i].num + 1;
		    		}
	    		}
    		}
    		if(response.code == 4003){
    			$scope.reminder = true;
    			$scope.message = response.message;
    		}
    	})
    	
    	//添加商品
    	var params = {
			goodsCode : k.code,
		    num : k.num
		};
		params = $.param(params);
    	$http({
	        method : "post",
	        dataType: "json",
			withCredentials: true,	//跨域名请求。XHR：XMLHttpRequest (XHR) ，基于XML技术的Http请求
		    crossDomain: true,
		    headers:{'Content-Type': 'application/x-www-form-urlencoded'},
		    data:params,
	        url : host + "/terminal/shoppingCart/add"
	    }).success(function(response){
	        if(response.code == 2000){
	        	$scope.reminder = true;
    			$scope.message = response.message;
	        }
	    }).error(function(response){
	    	console.log(JSON.stringify(response));
	    });
    }
    
})

